package com.androidmvc.base.core;

import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import com.androidmvc.base.utils.L;


public abstract class CoreEventHandler {

    public static final String LOG_TAG = "CoreEventHandler";
    protected Handler handler = new Handler();
    protected HandlerThread handlerThread;
    protected UCore uCore;

    protected CoreEventHandler() {
        L.d(LOG_TAG, "CoreEventHandler...");
        handlerThread = new HandlerThread(this.getClass().getSimpleName());
        final String className = this.getClass().getSimpleName();
        handlerThread.start();
        L.d(LOG_TAG, className + "handlerThread start...");
        handler = new Handler(handlerThread.getLooper()) {

            @Override
            public void handleMessage(Message msg) {
                try {
                    handleCoreEvent(msg.what, msg.obj);
                } catch (Exception e) {
                    L.d(e.getMessage(), className + " handler msg.what : " + msg.what + " ====" + e.toString());
                }
            }
        };
    }

    public void onExit() {
        if (handlerThread != null) {
            handlerThread.quit();
        }
    }

    public void postCoreEvent(int event, Object data) {
        if (handler != null) {
            handler.sendMessage(handler.obtainMessage(event, data));
        }
    }

    public void postCoreEvent(int event, Object data, boolean reset) {
        if (handler != null) {
            if (reset)
                handler.removeMessages(event);
            handler.sendMessage(handler.obtainMessage(event, data));
        }
    }

    public void postCoreEvent(final int event, final Object data, long delayMillis) {
        if (handler != null) {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    handler.sendMessage(handler.obtainMessage(event, data));
                }
            }, delayMillis);
        }
    }

    public boolean postSyncCoreEvent(int event, Object data) {
        return true;
    }

    public abstract void handleCoreEvent(int event, Object data);

    public void postCoreEventAtFirst(final int event, final Object data) {
        if (handler != null) {
            handler.postAtFrontOfQueue(new Runnable() {

                @Override
                public void run() {
                    handler.sendMessageAtFrontOfQueue(handler.obtainMessage(event, data));
                }
            });
        }
    }
}
